from urllib import request,parse
import json
import hashlib,time,random

def fanyi(keyword):
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

    salt = str(int(time.time() * 1000) + random.randint(0, 10))

    sign = "fanyideskweb" + keyword + salt + "ebSeFb%=XZ%T[KZ)c(sy!"

    m = hashlib.md5()
    m.update(sign.encode('utf-8')) 

    # 定义请求参数
    data = {'i': keyword,
            'from': 'AUTO',
            'to': 'AUTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'salt': salt,
            'sign': m.hexdigest(),
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_CLICKBUTTON',
            'typoResult': 'false',
            }
    data = parse.urlencode(data)
    headers = {
        'Cookie': 'OUTFOX_SEARCH_USER_ID=2084716981@114.111.166.79;',
        'Referer': 'http://fanyi.youdao.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; rv:51.0) Gecko/20100101 Firefox/51.0',
    }

    # 发送请求，抓取信息
    req = request.Request(url=url,data=bytes(data,encoding='utf-8'), headers=headers)
    res = request.urlopen(req)

    # 解析结果并输出
    str_json = res.read().decode('utf-8') # 获取响应的json字串
    myjson = json.loads(str_json) # 把json转字典
    #print(myjson)
    #info = myjson['translateResult'][0][0]['src'] + ":" + myjson['translateResult'][0][0]['tgt']
    info = myjson['translateResult'][0][0]['src'] + "  ->  " + myjson['smartResult']['entries'][1]
    print(info)

if __name__ == '__main__':
    while True:
        keyword = input('输入翻译的单词：')
        if keyword == 'q':
            break
        fanyi(keyword)
